package com.george.es.util;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.george.es.model.dto.WordDto;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;


/**
 * <p>
 *
 * </p>
 *
 * @author GeorgeChan 2019/6/17 15:55
 * @version 1.0
 * @since jdk1.8
 */
public class ReadWorldUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadWorldUtils.class);
    /**
     * 解析world文档
     * @param path 文件路径
     * @return 文本内容
     */
    public static WordDto readWorld(String path) {
        String buffer = StringPool.EMPTY;
        FileInputStream in2003;
        FileInputStream in2007;
        WordDto wordDto = new WordDto();
        try {
            if (StringUtils.endsWith(path, "doc")) {
                in2003 = new FileInputStream(new File(path));
                // 文档解析
                WordExtractor word2003 = new WordExtractor(in2003);
                // 获取文本
                buffer = word2003.getText();
                // 去除特殊符号
                buffer = DelSpecialCharPatternUtils.replaceBlank(buffer);
                // 获取图片
            } else if (StringUtils.endsWith(path, "docx")) {
                in2007 = new FileInputStream(new File(path));
                XWPFDocument doc2007=new XWPFDocument(in2007);
                List<XWPFPictureData> allPictures = doc2007.getAllPictures();
                // 获取图片
                int pictureType = allPictures.get(0).getPictureType();
                byte[] data = allPictures.get(0).getData();
                // 文档解析
                XWPFWordExtractor word2007=new XWPFWordExtractor(doc2007);
                // 获取文档内容
                buffer = word2007.getText();
                // 去除特殊符号
                buffer = DelSpecialCharPatternUtils.replaceBlank(buffer);
            } else {
                LOGGER.info("该文件不是world文档");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(path);
        // 文件名
        String name = file.getName();
        wordDto.setTitle(name);
        wordDto.setContent(buffer);
        wordDto.setCreateTime(new Date());
        wordDto.setUpdateTime(new Date());
        return wordDto;
    }

    public static void main(String[] args) {

        /**
         * 读取world文档测试
         */
        String path = "F:\\项目相关\\科华生物\\测试文档doc.doc";
        WordDto world = ReadWorldUtils.readWorld(path);
        System.out.println(world);
    }
}
